<?php
/**
 * Created by PhpStorm.
 * User: YD
 * Date: 2017/4/26
 * Time: 19:35
 */
namespace app\home\controller;
use app\home\common\Common;
use app\home\common\Page;
use app\infrastructure\uri\Request;
use app\infrastructure\uri\Uri;


class Systemmanage  extends Common
{
    private $client;
    public  function  __construct(){
        parent::__construct();
        $this->client=new Request();
    }
    /**
     *权限管理
     */
    public function authoritymanage(){
        $url=Uri::HOST.Uri::SELECTROLE;
        $roleData=$this->client->getArrayData($url);
//        dd($roleData);die;
        if($roleData['code'] != 0){
            $roleData=[];
        }else{
           $roleData=$roleData['data'];
        }
        $this->assign('list',$roleData);
//        if(\think\Request::instance()->isPost() && !empty(input('name'))) {
//            $startIndex=0;
//            $params=[
//                'platform'=>4,
//                'startIndex'=>$startIndex,
//                'pageSize'=>$pageSize,
//                'name'=>input('name')
//            ];
//            $data=$client->getArrayData($url,$params);
//        }else{
//            $p=empty(input('p'))?1:input('p');
//            $startIndex=($p-1)*10;
//            $params=[
//                'platform'=>4,
//                'startIndex'=>$startIndex,
//                'pageSize'=>$pageSize
//            ];
//            $data=$client->getArrayData($url,$params);
//            $count=$data['data']['totalCount'];
//            $pager=new Page($count,$pageSize,$p);
//            $page=$pager->show();
//            $this->assign('page',$page);
//        }
////        dd($data);
//        $this->assign('list',$data['data']['dataList']);
        return view();
    }

    /**
     *为角色设置权限
     */
    public function  setauthority(){
        $id=input('id');
        if(\think\Request::instance()->isAjax()){
            if(!empty($_POST['idd'])){
                $resourceIds=json_encode($_POST['idd']);
            }else{
                $resourceIds='';
            }
            $data=[
                'content'=>$resourceIds
            ];
            $updateRole=Uri::HOST.Uri::UPDATEROLE.$id;
            $res=$this->client->getArrayData($updateRole,$data,4);
            return $res;
//            $url=Uri::AUTHORITYHOST.Uri::ASSIGNRESOURCE;
//            $res=$client->getArrayData($url,$params,3);
//            if(!$res['code']){
//                return ['valid'=>1,'msg'=>'操作成功'];
//            }else{
//                return ['valid'=>0,'msg'=>'操作失败'];
//            }
        }
//        读取所有的权限
        $url=Uri::HOST.Uri::SELECTROLE."?id=".$id;
        $data=$this->client->getArrayData($url);
            $data=$data['data'][0];
        $authId=$data['content'];
        $authId=json_decode($authId);
        if(!empty($authId)){
            $query=[];
            $authUrl=Uri::HOST.Uri::POSTSELECTAUTH;
           $query['id']=$authId;
            $auth=$this->client->getArrayData($authUrl,$query,3);
            if($auth['code'] != 0){
             $auth=[];
            }else{
             $auth=$auth['data'];
            }
        }else{
            $auth=[];
        }
//        die;
        //查找所有一级权限
//        $firstAuth=Uri::HOST.Uri::SELECTAUTH."?parent_id=0";
//        $firstAuthData=$this->client->getArrayData($firstAuth);
//        $firstAuthData=$firstAuthData['data'];
//        dd($firstAuthData);
        //获取ID
//        $firstAuthId=[];
//        foreach($firstAuthData as $k=>$v){
//            $firstAuthId[$k][]=$v['id'];
//        }
        //查找所有一级权限的二级权限
//        foreach($firstAuthData as $k=>$v){
//           $secondUrl=Uri::HOST.Uri::SELECTAUTH."?parent_id=".$v['id'];
//            $secondData=$this->client->getArrayData($secondUrl);
//            if($secondData['code'] == 0){
//            $secondData=$secondData['data'][0];
//            $firstAuthData[$k]['child']=$secondData;
//            }
//            dd($secondData);
//            dd($secondUrl);
//        }
         //读取所有权限
        $authList=Uri::HOST.Uri::SELECTAUTH;
        $authListData=$this->client->getArrayData($authList);
        if($authListData['code'] != 0){
           $authListData=[];
        }else{
            $authListData=$authListData['data'];
        }
//        dd($auth);
        $newauth=[];
        foreach($auth as $k=>$v){
            $newauth[]=$v['id'];
        }
        $this->assign('list',$newauth);
        $this->assign('data',$authListData);
//        dd($list);
//        $this->assign('data',$data['data']['dataList']);
//        dd($data['data']['dataList']);
        return view();
    }

    //  递归树形结构
    public function tree($authorityList,$pid=1){
        $last=array();
        foreach($authorityList as &$v){
            if($v['parentId']==$pid){
                $v['sub']=$this->tree($authorityList,$v['id']);
                $last[]=$v;
            }
        }
        return $last;
    }


    /**
     * 权限列表
     */
    public function authlist(){
        $url=Uri::HOST.Uri::SELECTAUTH;
        $client=new Request();
        $data=$this->client->getArrayData($url);
       if($data['code'] != 0){
           $data=[];
       }else{
           $data=$data['data'];
       }
//        dd($data);
        $this->assign('list',$data);
//        dd($data);
        return view();
    }
    /**
     * 权限添加
     */
    public function authadd(){
        if(\think\Request::instance()->isPost()){
            $data=input('');
            $url=Uri::HOST.Uri::SELECTAUTH;
            $params=[
              'name'=>$data['name'],
              'status'=>$data['status'],
              'content'=>$data['resourcePath'],
              'parent_id'=>$data['parentId']
            ];
            $res=$this->client->getArrayData($url,$params,3);
              if(!$res['code']){
                   $this->success('添加成功',URL('home/Systemmanage/authlist'));
              }else{
                  $this->error('添加失败');
              }
        }
        return view();
    }

    /**
     * 权限编辑
     */
    public function authedit(){
        //读取旧数据
        $id=$_GET['id'];
        $operatorId=session('userid');
        $url=Uri::HOST.Uri::SELECTAUTH."?id=".$id;
        $olddata=$this->client->getArrayData($url);
        $olddata=$olddata['data'][0];
        if(\think\Request::instance()->isPost()){
            $url=Uri::HOST.Uri::EDITAUTH.$id;
            $params=[
                'status'=>$_POST['status'],
                'name'=>$_POST['authName'],
                'content'=>$_POST['resourcePath'],
                'parent_id'=>$_POST['parentId']
            ];
            $res=$this->client->getArrayData($url,$params,4);
             if(!$res['code']){
                $this->success($res['msg'],URL('home/systemmanage/authlist'));
             }else{
                 $this->error($res['msg']);
             }
        }
        $this->assign('olddata',$olddata);
     return view();
    }

    /**
     * 用户管理
     */
    public  function userManage(){
        if(isset($_GET['name']) && !empty($_GET['name'])){
            $url=Uri::HOST.Uri::SELECTADMINUSER.'?name='.$_GET['name'];
        }else{
            $url=Uri::HOST.Uri::SELECTADMINUSER;
        }
        $adminUser=$this->client->getArrayData($url);
        if($adminUser['code'] != 0){
            $adminUser=[];
        }else{
            $adminUser=$adminUser['data'];
        }
//        dd($adminUser);
        $this->assign('list',$adminUser);
//        $pageSize=10;
//        if(\think\Request::instance()->isPost()) {
//            $startIndex=0;
//            $params=[
//                'startIndex'=>$startIndex	,
//                'pageSize'=>$pageSize,
//                'name'=>input('name')
//            ];
////            dd($params);
//            $data=$client->getArrayData($url,$params);
//        }else{
//            $p=empty(input('p'))?1:input('p');
//            $startIndex=($p-1)*10;
//            $params=[
//                'startIndex'=>$startIndex	,
//                'pageSize'=>$pageSize
//            ];
//            $data=$client->getArrayData($url,$params);
//            $count=$data['data']['totalCount'];
//            $pager=new Page($count,$pageSize,$p);
//            $page=$pager->show();
//            $this->assign('page',$page);
//        }
//        dd($data);
        return view();
    }
    /**
     * 设置角色页面
     */
    public function setrole(){
        //获取用户信息
        $id = input('id');
        $uri = Uri::HOST.Uri::SELECTADMINUSER."?id=".$id;
        $data = $this->client->getArrayData($uri);
         if($data['code'] != 0){
             $data=[];
         }else{
             $data=$data['data'][0];
         }
        $this->assign('user', $data);

        $uri = Uri::HOST.Uri::SELECTROLE;
        $role = $this->client->getArrayData($uri);
        if($role['code'] != 0){
            $role=[];
        }else{
            $role=$role['data'];
        }
        $isSetrole=json_decode($data['role']);
        if(!empty($isSetrole)){
            foreach($role as $k=>$v){
                if(in_array($v['id'],$isSetrole)){
                    $role[$k]['isSetRole']=true;
                }
            }
        }

        $this->assign('role', $role);
        return view();
    }
    /**
     * 为用户设置角色，保存动作
     */
    public function setRoleForUser(){
        if(\think\Request::instance()->isAjax()){
            if(isset($_POST['searchable'])){
                $roles=$_POST['searchable'];
            }else {
                $roles=[];
            }
            $roles=json_encode($roles);
            $user_id=$_POST['userid'];
             $updateadminuserUrl=Uri::HOST.Uri::UPDATEADMINUSER.$user_id;
            $data=[
                'role'=>$roles
            ];
            $res=$this->client->getArrayData($updateadminuserUrl,$data,4);
            return $res;
        }
    }
    /**
     * 角色添加
     */
    public function addgroup(){
        if(\think\Request::instance()->isPost()){
            $url=Uri::HOST.Uri::ADDROLE;
            $params=[
                'name'=>input('name'),
                'status'=>input('status'),
                'num'=>input('num'),
                'content'=>''
            ];
            $res=$this->client->getArrayData($url,$params,3);
             if(!$res['code']){
                 $this->success($res['msg'],URL('home/systemmanage/authoritymanage'));
             }else{
                 $this->error($res['msg']);
             }
        }
        return view();
    }
    /**
     * 角色删除
     */
    public function delrole(){
        if(\think\Request::instance()->isAjax()){
            $id=input('id');
            $type=input('type');
            $operatorId=session('userid');
            $url=Uri::HOST.Uri::UPDATEROLE.$id;
            if($type == 1){
                $params=[
                    'status'=>1
                ];
            }else{
                $params=[
                    'status'=>0
                ];
            }
            $res=$this->client->getArrayData($url,$params,4);
            if(!$res['code']){
               return ['valid'=>1,'msg'=>$res['msg']];
            }else{
                return ['valid'=>0,'msg'=>$res['msg']];
            }
        }
    }

    /**
     * 通过cURL可以使用URL的语法模拟浏览器来传输数据，
     * @param $url    请求地址
     * @param array $post  请求的数据
     */
    public function curl($url,$postData=[]){
        $ch = curl_init();
        curl_setopt( $ch , CURLOPT_URL , $url );
        curl_setopt( $ch , CURLOPT_RETURNTRANSFER , 1 );
        curl_setopt( $ch , CURLOPT_SSL_VERIFYPEER , false );
        curl_setopt( $ch , CURLOPT_SSL_VERIFYHOST , false );
        //如果是post提交
        if ( $postData ) {
            curl_setopt( $ch , CURLOPT_TIMEOUT , 30 );
            curl_setopt( $ch , CURLOPT_POST , 1 );
            curl_setopt( $ch , CURLOPT_POSTFIELDS , $postData );
        }
        //执行
        $data = '';
        if ( curl_exec( $ch ) ) {
            $data = curl_multi_getcontent( $ch );
        }
        curl_close( $ch );
        return $data;
    }



    /**
     * 添加新用户
     */
    public function  addNewUser(){
      if(\think\Request::instance()->isPost()){
          $url=Uri::HOST.Uri::ADDADMINUSER;
          $data=[
              'name'=>$_POST['name'],
              'password'=>$_POST['password'],
              'type'=>$_POST['type']
          ];
          $res=$this->client->getArrayData($url,$data,3);
          if(!$res['code']){
              $this->success($res['msg'],URL('home/systemmanage/userManage'));
          }else{
              $this->error($res['msg']);
          }
      }
        return view();
    }



}